import editForm from "./form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { CategoryListTree, CategoryAdd, CategoryDelete, CategoryEdit, CategoryList } from "@/api/pms/catogory";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "./types";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";

export function useMenu() {
    const form = reactive({
        title: ""
    });

    const formRef = ref();
    const dataList = ref([]);
    const loading = ref(true);



    const columns: TableColumnList = [
        {
            label: "分类名称",
            prop: "name",
            align: "left",

        },
        {
            label: "分类图标",
            prop: "icon",
            width: 100,

        },

        {
            label: "计量单位",
            prop: "productUnit"
        },

        {
            label: "所属店铺",
            prop: "storeId"
        },
        {
            label: "排序",
            prop: "sort",
            width: 100
        },
        {
            label: "显示状态",
            prop: "showStatus",
            formatter: ({ visible }) => (visible == "1" ? "显示 " : "隐藏"),
            width: 100
        },
        {
            label: "操作",
            fixed: "right",
            width: 210,
            slot: "operation"
        }
    ];

    function handleSelectionChange(val) {
        console.log("handleSelectionChange", val);
    }

    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }

    async function onSearch() {
        loading.value = true;
        // const result = await CategoryListTree({ name: form.title }); // 这里是返回一维数组结构，前端自行处理成树结构，返回格式要求：唯一id加父节点parentId，parentId取父节点id

        const result = await CategoryList({
            pageIndex: 1,
            pageSize: 99999,
            name: form.title
        });
        if (result.success) {
            dataList.value = result.data;
            loading.value = false;
        }

    }

    function formatHigherMenuOptions(treeList) {
        if (!treeList || !treeList.length) return;
        const newTreeList = [];
        for (let i = 0; i < treeList.length; i++) {
            treeList[i].title = transformI18n(treeList[i].title);
            // treeList[i].isLeaf = treeList[i].menuType != 'A';
            treeList[i].disabled = treeList[i].menuType == 'A'//treeList[i].status === 1 ? true : false;
            formatHigherMenuOptions(treeList[i].children);
            newTreeList.push(treeList[i]);
        }
        return newTreeList;
    }

    function openDialog(title = "新增", row?: FormItemProps) {
        console.log("row", row);
        let formInline = {};

        let higherMenuOptions = formatHigherMenuOptions(cloneDeep(dataList.value));

        higherMenuOptions = [{
            id: "0",
            name: "默认分类",
            parentCid: -1,
            catLevel: 0,
            showStatus: 1,
            children: []
        }].concat(higherMenuOptions);

        if (title != "新增") {
            formInline = {
                higherMenuOptions: higherMenuOptions,
                id: row?.id,
                parentCid: row?.parentCid ? parseInt(row?.parentCid) : 0,
                parentId: row?.parentCid,
                name: row?.name,
                catLevel: row?.catLevel,
                showStatus: row?.showStatus,
                sort: row?.sort,
                icon: row?.icon,
                productUnit: row?.productUnit,
                productCount: row?.productCount,
                type: row?.type,
                storeId: row?.storeId,
                enableStatus: row?.enableStatus,
                createBy: row?.createBy,
                createTime: row?.createTime,
                updateBy: row?.updateBy,
                updateTime: row?.updateTime,
            }
        } else {
            formInline = {
                higherMenuOptions: higherMenuOptions,
                id: undefined,
                parentCid: 0,
                parentId: 0,
                name: "",
                catLevel: "",
                showStatus: 1,
                sort: 10,
                icon: "",
                productUnit: "",
                productCount: 0,
                type: 1,
                storeId: "",
                enableStatus: 1
            }


        }

        addDialog({
            title: `${title}分类`,
            props: {
                formInline
            },
            width: "45%",
            draggable: true,
            fullscreen: deviceDetection(),
            fullscreenIcon: true,
            closeOnClickModal: false,
            contentRenderer: () => h(editForm, { ref: formRef }),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;
                function chores() {
                    let apiFun = title === "新增" ? CategoryAdd : CategoryEdit;
                    apiFun(curData).then((result) => {
                        if (result.success) {
                            message(
                                `操作成功`,
                                {
                                    type: "success"
                                }
                            );
                            done(); // 关闭弹框
                            onSearch(); // 刷新表格数据
                        }
                    }).catch((err) => {
                        message(
                            err?.message ? err?.message : `操作F成功`,
                            {
                                type: "error"
                            }
                        );
                    });

                }
                FormRef.validate(valid => {
                    if (valid) {
                        console.log("curData", curData);
                        // 表单规则校验通过
                        chores()
                    }
                });
            }
        });
    }

    function handleDelete(row) {
        CategoryDelete([row.id]).then((res) => {
            if (res.success) {
                message(`操作成功`, {
                    type: "success"
                });

                onSearch();
            }
        }).catch((err) => {
            message(err?.message ? err?.message : `操作失败`, {
                type: "error"
            });
        });

    }

    onMounted(() => {
        onSearch();
    });

    return {
        form,
        loading,
        columns,
        dataList,
        /** 搜索 */
        onSearch,
        /** 重置 */
        resetForm,
        /** 新增、修改菜单 */
        openDialog,
        /** 删除菜单 */
        handleDelete,
        handleSelectionChange
    };
}
